//
//  SearchItemCell.swift
//  GhostWorld
//
//  Created by Kam on 2018/8/1.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit

class SearchItemCell: UITableViewCell {
  
  // MARK: - IBOutlets
  
  @IBOutlet private weak var searchItemContentView: UIView!
  @IBOutlet private weak var nameLabel: UILabel!
  @IBOutlet private weak var coverImageView: UIImageView!
  @IBOutlet private weak var vipIcon: UIImageView!
  
  // MARK: - Private vars
  
  private let selectView = UIView()
  
  // MARK: - Private methods
  
  
  
  // MARK: - Public vars
  
  
  
  // MARK: - Lifecycle
  
  override func awakeFromNib() {
    super.awakeFromNib()
    
    searchItemContentView.layer.cornerRadius = 4
    searchItemContentView.clipsToBounds = true
    
    // selected background view
    let backgroundView = UIView()
    backgroundView.backgroundColor = .clear
    
    selectView.backgroundColor = UIColor(fromRGB: 0x98000C)
    selectView.clipsToBounds = true
    selectView.layer.cornerRadius = 4
    backgroundView.addSubview(selectView)
    selectedBackgroundView = backgroundView
  }
  
  override func layoutSubviews() {
    super.layoutSubviews()
    
    selectView.frame = searchItemContentView.frame
  }
  
  override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    
    // Configure the view for the selected state
  }
  

  
  // MARK: - Public methods
  
  func prepare(coverImageURL: URL?, contentName: String, isVipAlbum: Bool, keyword: String?) {
    if let url = coverImageURL {
      coverImageView.af_setImage(withURL: url)
    }
    vipIcon.isHidden = !isVipAlbum
    
    // highlight keyword
    self.nameLabel.text = contentName
    if let count = keyword?.count, count > 0 {
      let attributes: [NSAttributedString.Key : Any] = [
        NSAttributedString.Key.foregroundColor: nameLabel.textColor,
        NSAttributedString.Key.font: nameLabel.font
      ]
      let attributedContentName = NSMutableAttributedString(string: contentName, attributes: attributes)
      let keywordsArray = keyword!.components(separatedBy: " ")
      
      keywordsArray.forEach { keyword in
        if keyword.count > 0 {
          if let range = contentName.range(of: keyword) {
            let highlightAttributes: [NSAttributedString.Key : Any] = [
              NSAttributedString.Key.foregroundColor: UIColor(fromPreeset: .globalTint)
            ]
            attributedContentName.setAttributes(highlightAttributes, range: NSRange(range: range, in: contentName))
          }
        }
      }
      
      self.nameLabel.attributedText = attributedContentName;
    }
  }
}

extension SearchItemCell {
  static let defaultHeight: CGFloat = 90
}
